package com.shujia.flink.state;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Properties;

public class Demo5KafkaExactlyOnce {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //构建kafka source
        KafkaSource<String> source = KafkaSource.<String>builder()
                //指定broker列表
                .setBootstrapServers("master:9092,node1:9092,node2:9092")
                //指定topic
                .setTopics("in")
                //消费者组
                .setGroupId("my-group")
                //指定读取数据的位置：earliest：读取最早的数据, latest: 读取最新的数据
                .setStartingOffsets(OffsetsInitializer.earliest())
                //读取数据的格式
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .build();

        //使用 kafka source
        DataStreamSource<String> kafkaDS = env
                .fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source");


        //堆数据进行清洗过滤
        SingleOutputStreamOperator<String> filterDS = kafkaDS
                .filter(word -> !"java".equals(word));

        Properties properties = new Properties();
        //设置事务超时时间
        properties.setProperty("transaction.timeout.ms", String.valueOf(10 * 60 * 1000));

        //创建kafka sink
        KafkaSink<String> sink = KafkaSink.<String>builder()
                //kafka broker列表
                .setBootstrapServers("master:9092,node1:9092,node2:9092")
                //指定而外的配置
                .setKafkaProducerConfig(properties)
                //指定数据的格式
                .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                        //指定topic,如果topic不存在会自动创建一个分区为1副本为1的topic
                        .setTopic("out1")
                        //指定数据格式
                        .setValueSerializationSchema(new SimpleStringSchema())
                        .build()
                )
                //指定数据处理的语义
                //EXACTLY_ONCE：唯一一次，flink会将两次checkpoint中间的结果放到一个事务中，要么都成功要么都失败
                .setDeliverGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
                .build();

        filterDS.sinkTo(sink);

        env.execute();
    }
}
